
package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.CommodityEntity;
import com.weiqiao.mall.repository.ICardCommodityRepository;
import com.weiqiao.mall.repository.ICommodityRepository;
import com.weiqiao.mall.service.ICommodityService;
import com.weiqiao.utils.MallUtil;
import com.weiqiao.utils.WeiXinUtils;
import com.weiqiao.utils.PageUtil;
import com.weiqiao.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Pattern;

@Service("CommodityServiceImpl")
public class CommodityServiceImpl implements ICommodityService {

    /**
     * 商品管理数据层
     */
    @Autowired
    private ICommodityRepository commodityRepository;

    /**
     * 产品管理（信用卡）数据层
     */
    @Autowired
    private ICardCommodityRepository cardCommodityRepository;

    @Override
    public List<CommodityEntity> findCommoditys(int companyId, Bson filter) {
        List<CommodityEntity> commodity = new ArrayList<>();
        List<String> list = commodityRepository.findCommoditys(companyId, filter);
        for (String info : list) {
            CommodityEntity entity = new Gson().fromJson(info, CommodityEntity.class);
            entity.setCreate_date(this.formateTime(entity.getCreate_date()));
            commodity.add(entity);
        }
        return commodity;
    }

    /**
     * 转换时间戳为时间字符串
     */
    public String formateTime(String dateStr) {
        try {
            if (StringUtil.isLong(dateStr)) {
                String date = WeiXinUtils.format(new Date(Long.parseLong(dateStr)), "yyyy-MM-dd HH:mm");
                dateStr = date;
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return dateStr;
    }

    @Override
    public int countCommodity(int companyId, Bson bson) {
        return commodityRepository.countCommodity(companyId, bson);
    }

    @Override
    public boolean updateCommodityByJson(int companyId, Bson filter, String json) {

        return commodityRepository.updateOneCommodityByJson(companyId, filter, json);
    }

    @Override
    public CommodityEntity findCommodityById(String commodity_id, int company_id) {
        Bson filter = Filters.and(Filters.eq("commodity_id", commodity_id), Filters.eq("company_id", company_id));
        String s = commodityRepository.findCommodityById(company_id, filter);
        return new Gson().fromJson(s, CommodityEntity.class);
    }

    @Override
    public List<String> getCommodityIdAndLimit(int companyId, Bson filter, int limit) {
        Gson gson = new Gson();
        List<String> result = new ArrayList<>();
        List<String> list = commodityRepository.findCommodityAndLimit(companyId, filter, limit);
        for (String a : list) {
            CommodityEntity info = gson.fromJson(a, CommodityEntity.class);
            result.add(info.getCommodity_id());
        }
        return result;
    }


    /**
     * 商品管理--查询商品
     *
     * @param request
     * @param pageable
     * @return
     */
    @Override
    public Map findCommoditys(HttpServletRequest request, Pageable pageable) {
        int companyId = MallUtil.getCompanyId(request);
        String label_brand_id = request.getParameter("label_brand_id");
        String commodityName = request.getParameter("commodity_name");
        List<String> labelIdList = new ArrayList<>();
        labelIdList.add(label_brand_id);
        Bson filter = Filters.and(Filters.eq("company_id", companyId), Filters.eq("delete_flag", 0),
                Filters.in("label_brand_ids", labelIdList));
        if (StringUtils.isNotBlank(commodityName)) {
            Pattern pattern = Pattern.compile("^.*" + commodityName + ".*$", Pattern.CASE_INSENSITIVE);
            filter = Filters.and(filter, Filters.eq("name", pattern));
        }
        List<String> list = commodityRepository.findCommodityByFilterAndPage(companyId, filter, pageable);
        List<CommodityEntity> commodityList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (String a : list) {
                CommodityEntity c = new Gson().fromJson(a, CommodityEntity.class);
                c.setCreate_date(this.formateTime(c.getCreate_date()));
                commodityList.add(c);
            }
        }
        int total = this.countCommodity(companyId, filter);
        return PageUtil.toPage(commodityList, total);
    }

    @Override
    public boolean updateTagImage(int company_id, List<String> commodity_ids, String cover_tag_img, String detail_tag_img) {
        if (CollectionUtils.isEmpty(commodity_ids) ||
                (StringUtil.isBlank(cover_tag_img) && StringUtil.isBlank(detail_tag_img))) {
            return false;
        }
        Document commodity_doc = new Document("company_id", company_id);
        commodity_doc.append("commodity_id", new Document("$in", commodity_ids));
        Document update_doc = new Document();
        if (!StringUtil.isBlank(cover_tag_img)) {
            update_doc.append("cover_tag_img", cover_tag_img);
        } else {
            update_doc.append("detail_tag_img", detail_tag_img);
        }
        return commodityRepository.updateMany(company_id, commodity_doc, update_doc, false);
    }
}
